import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { ReactElement, Ref, useContext, useRef, useState } from 'react';
import { ContractManageAPI } from '../common/type';
import { Spin, Upload, UploadFile, UploadProps, message } from 'antd';
import { InboxOutlined, FileExcelOutlined, DeleteOutlined } from '@ant-design/icons';
import { getFileNameNotType, getKeyRouter, getLoadMapList, getTenant, getTenantID, onCloseModalCommon } from '@/utils';
import { getBaseUrl } from '@/services/urlconst';
import { ConractControllerContext, IContractsActionEnum } from '../common';
import { ILoadMapTypeAll } from '@/common';
import moment from 'moment';
const baseUrl = getBaseUrl();

export const OpenMaterialImportModal: React.FC<ContractManageAPI.IOpenMaterialImportModal> = ({ onClose, setMaterialDataSource }) => {
  /**弹框的ref*/
  const importMaterialModalRef: Ref<IOneModalRef> = useRef(null);

  const { styleFixCls, contractForm, contarctJsonList, contractDispatch } = useContext(ConractControllerContext);

  /** 获取数据字典loadMdicMap */
  const { loadMapInfo, mapLoading }: Record<string, any> = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`, //单位
  ]);

  /** 保存导入数据和接口loading */
  const [importDataInfo, setImPortDataInfo] = useState<Record<string, any>>({
    importLoading: false,
    importList: [],
  });

  /** 处理物料数据 */
  const handleMaterialList = (data: Record<string, any>[]) => {
    const loadInfoObj: Record<string, any>[] = loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`];
    let newMaterList: object[] = [];
    data?.forEach((item: any) => {
      const unitCodeInfo: object | any = loadInfoObj?.find((itemFind: any) => itemFind?.name == item?.unitBusinessName);
      let itemObj: Record<string, any> = {
        id: item?.id,
        key: `detailList-${getKeyRouter()}`,
        materialID: item?.materialID,
        materialName: item?.materialName ? item?.materialName : null,
        materialNum: item?.materialNum,
        specInfo: item?.specInfo ? item?.specInfo : null,
        priceInTax: item?.priceInTax ? item?.priceInTax : 0,
        deliveryTime: item?.deliveryTime ? moment(item?.deliveryTime) : null,
        deliveryAddress: item?.deliveryAddress ? item?.deliveryAddress : null,
        deliveryStyle: item?.deliveryStyle ? item?.deliveryStyle : null,
        taxRate: item?.taxRate ? item?.taxRate : contractForm?.getFieldValue('taxRate'),
        unitBusiness: unitCodeInfo?.id ? unitCodeInfo?.id : item?.unitBusinessName,
        unitBusinessName: item?.unitBusinessName,
        expectNum: item?.expectNum ? item?.expectNum : null,
        sumInTax: item?.sumInTax ? item?.sumInTax : 0,
        versionNum: 0,
        modifyFlag: '0',
      };
      newMaterList?.push(itemObj);
    });
    return newMaterList;
  };
  /* 上传 */
  const uploadProps: UploadProps = {
    accept: '.xls,.xlsx',
    headers: {
      tenantName: getTenant(),
    },
    name: 'attachFile',
    maxCount: 1,
    method: 'POST',
    action: `${baseUrl}/contractController/importDetails?=${Math.random()}`,
    onChange(info) {
      if (info.file.status == 'uploading') {
        setImPortDataInfo({
          ...importDataInfo,
          importLoading: true,
        });
      }
      if (info.file.status == 'done') {
        if (info.file?.response) {
          if (info.file?.response?.msgFlag) {
            message.success(`${info.file.name} 上传成功`);
            setImPortDataInfo({
              importList: info.file?.response?.obj ? handleMaterialList(info.file?.response?.obj) : [],
              importLoading: false,
            });
          } else {
            setImPortDataInfo({
              importList: [],
              importLoading: false,
            });
          }
        }
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
        setImPortDataInfo({
          importList: [],
          importLoading: false,
        });
      }
    },
    itemRender: (_originNode: ReactElement, file: UploadFile, _fileList: object[], actions: any) => {
      if (file?.status == 'done') {
        return (
          <div className={`${styleFixCls}importMaterialBox-fieldDomBox`}>
            <div>
              <a>
                <FileExcelOutlined />
              </a>
              &nbsp;
              {file?.name ? getFileNameNotType(file?.name, 15) : '--'}
            </div>
            <a
              style={{ color: 'red' }}
              onClick={() => {
                setImPortDataInfo({
                  importList: [],
                  importLoading: false,
                });
                actions?.remove();
              }}
            >
              <DeleteOutlined />
            </a>
          </div>
        );
      } else {
        return <></>;
      }
    },
    // onRemove: (file) => {
    //   console.log(".ant-upload-list==========",file)
    //   if (file) {
    //     setImPortDataInfo({
    //       importList: [],
    //       importLoading: false,
    //     });
    //   }
    // },
  };

  /** 保存 */
  const onSave = () => {
    const { importList } = importDataInfo;
    if (importList && importList?.length > 0) {
      const getFormDetail: object[] = contractForm?.getFieldValue('detailList');
      const detailList: Record<string, any>[] = contarctJsonList?.detailList?.length > 0 ? contarctJsonList?.detailList : [];
      const formDetailList: Record<string, any>[] = getFormDetail?.length > 0 ? getFormDetail : [];
      contractDispatch({
        type: IContractsActionEnum.CONTRACT_JSONLIST,
        payload: {
          ...contarctJsonList,
          detailList: [...detailList, ...importList],
        },
      });
      // contractForm.setFieldsValue({
      //   detailList: [...formDetailList, ...importList]
      // });
      setMaterialDataSource([...formDetailList, ...importList]);
      onCloseModalCommon(importMaterialModalRef);
    } else {
      message.warning('请上传文件！！！');
    }
  };

  /** 物料模板下载 */
  const materialTempDown = () => {
    message.success('下载中，请稍后...');
    let DownloadLink = document.createElement('a');
    DownloadLink.href = `${getBaseUrl()}/hrky/file/contract/detail/供货服务清单模板.xlsx`;
    DownloadLink.download = '供货服务清单模板.xlsx';
    document.body.appendChild(DownloadLink);
    DownloadLink.click(); // 触发a标签的click事件
    document.body.removeChild(DownloadLink);
  };

  return (
    <OneModal
      open={true}
      getContainer={false}
      ref={importMaterialModalRef}
      title={'导入供货/服务清单'}
      onCancel={onClose}
      width={document.body.clientWidth * 0.3}
      bodyStyle={{
        padding: '10px',
      }}
      onOk={onSave}
      confirmLoading={importDataInfo?.importLoading || mapLoading}
    >
      <Spin spinning={importDataInfo?.importLoading || mapLoading}>
        <div className={`${styleFixCls}importMaterialBox`}>
          <Upload.Dragger {...uploadProps}>
            <div>
              <a>
                <InboxOutlined style={{ fontSize: 48 }} />
              </a>
              <div>
                将文件拖到此处，或&nbsp;
                <a>点击上传</a>
              </div>
            </div>
          </Upload.Dragger>
          <div style={{ marginTop: 5 }} slot="tip">
            • 文件格式保证正确（仅支持.xlsx .xls文件）
            <a onClick={materialTempDown}>下载模板</a>
          </div>
        </div>
      </Spin>
    </OneModal>
  );
};
